
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../api/DictApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/StoreData.dart';
import '../../../utils/Utils.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart';
import 'LFormMultiSelectState.dart';
import 'SelectList.dart';



class LFormMultiSelectLogic extends MyController{


  final state = LFormMultiSelectState();

  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData;
    state.defaultText = "";
    state.resultOptions = [];
    state.dictOptions = [];
    state.betweenSign = betweenSign??"";
    state.formTag = formTag;
    state.formType = formType;
    state.checkVals = [];

    //初始化下拉数据
    initDict();
  }

  ///初始化下拉数据
  initDict()async{
    ///是否人为给了下拉信息
    if(!Utils.isEmpty(state.formItem["options"])){
      state.dictOptions = state.formItem["options"];
      initDefaultValue();
      update();
      return;
    }

    if(Utils.isEmpty(state.formItem["dictCode"])){
      return;
    }
    //初始化数据字典信息
    List dictCodeReplaceFields = [];
    if(!Utils.isEmpty(state.formItem['replaceFields'])){
      dictCodeReplaceFields.add({'dictCode':'${state.formItem["dictCode"]}','replaceFields':state.formItem['replaceFields']});
    }
    await DictApi.initDict(state.formItem["dictCode"], "", dictCodeReplaceFields);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    state.dictOptions = state.resultOptions;
    initDefaultValue();
    update();
  }

  initDefaultValue(){
    late List li;
    for(int i=0;i<state.dictOptions.length;i++ ){
      state.checkVals.add(false);
      if(!Utils.isEmpty(state.formData['${state.formItem["field"]}${state.betweenSign}'])){
        li = state.formData['${state.formItem["field"]}${state.betweenSign}'].toString().split(",");
        if(li.contains(state.dictOptions[i]["itemValue"])){
          state.defaultText += "${state.dictOptions[i]["itemText"]},";
          state.checkVals.add(true);
        }
      }
    }

    ///如果是多选，将最后一个,去掉
    if(!Utils.isEmpty(state.defaultText)){
      state.defaultText = state.defaultText.substring(0, state.defaultText.lastIndexOf(','));//将字符串最后面字符去掉 all为数组
    }
  }




  //当数据字典编号发生变化
  void updateDictCode() async{
    if(Utils.isEmpty(state.formItem["dictCode"])){
      return;
    }
    //初始化数据字典信息
    List dictCodeReplaceFields = [];
    if(state.formItem['replaceFields']!=null){
      dictCodeReplaceFields.add({'dictCode':'${state.formItem["dictCode"]}','replaceFields':state.formItem['replaceFields']});
    }
    await DictApi.initDict(state.formItem["dictCode"], "", dictCodeReplaceFields);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    state.dictOptions = state.resultOptions;
    initDefaultValue();
    update();
  }




  dynamic onValidator(v){
    //非空验证
    if (state.formItem["required"] == true && (v == null || v.isEmpty || v.trim().isEmpty)) {
      return "${state.formItem["label"]}不能为空";
    }
    return null;
  }

  //清空选择
  void onClear(){
    //清空选择的内容
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
    state.defaultText = "";
    for(int i=0;i<state.checkVals.length;i++){
      state.checkVals[i]=false;
    }
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':null});
    }
    update();
  }

  //选择
  void onSelected(){
    state.defaultText="";
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = "";
    for(int i=0;i<state.checkVals.length;i++){
      if(state.checkVals[i]){
        state.defaultText += "${state.dictOptions[i]["itemText"]},";
        state.formData['${state.formItem["field"]}${state.betweenSign}'] += "${state.dictOptions[i]["itemValue"]},";
      }
    }
    if(!Utils.isEmpty(state.defaultText)){
      state.defaultText = state.defaultText.substring(0, state.defaultText.lastIndexOf(','));//将字符串最后面字符去掉 all为数组
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = state.formData['${state.formItem["field"]}${state.betweenSign}'].substring(0, state.formData['${state.formItem["field"]}${state.betweenSign}'].lastIndexOf(','));
    }else{
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
    }
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.formData['${state.formItem["field"]}${state.betweenSign}']});
    }
    update();
  }


  Future<dynamic> showCustomModalBottomSheet(context, tag) async {
    if(state.dictOptions.isEmpty){
      return null;
    }

    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {

        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 2.0,
          child: Column(children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  Align(
                    alignment: Alignment.topLeft,
                    child: IconButton(
                      icon: const Icon(Icons.delete_forever_rounded),
                      onPressed: () {
                        Get.back();
                        onClear();
                      }),
                  ),
                  Center(
                    child: Text(
                      '${state.formItem["label"]}选择',
                      style: const TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 16.0),
                    ),
                  ),
                  TextButton(
                    onPressed:(){
                      Get.back();
                      onSelected();
                    } ,
                    child: const Text('确定',style: TextStyle(fontSize: 16,)),
                  )
                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: SelectListPage(dictOptions: state.dictOptions,checkVals: state.checkVals,),
            ),
          ]),
        );
      },
    );
  }

  ///如果是QUERYFORM 重置，需要将显示值清空
  @override
  void reset(){
    state.defaultText="";
    update();
  }
}

